package com.ljyhhh.SmartCity.utils


import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.AttributeSet
import android.widget.Toast
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL

class MyImageView(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : androidx.appcompat.widget.AppCompatImageView(context, attrs, defStyleAttr) {

    companion object {
        const val GET_DATA_SUCCESS = 1
        const val NETWORK_ERROR = 2
        const val SERVER_ERROR = 3
    }
//    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) :
//            super(context, attrs, defStyleAttr)
    constructor(context: Context) : this(context, null, 0)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    private val handler = @SuppressLint("HandlerLeak")
    object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                GET_DATA_SUCCESS -> {
                    val bitmap = msg.obj as Bitmap
                    setImageBitmap(bitmap)
                }
                NETWORK_ERROR -> Toast.makeText(context, "网络连接失败", Toast.LENGTH_SHORT).show()
                SERVER_ERROR -> Toast.makeText(context, "服务器发生错误", Toast.LENGTH_SHORT).show()
            }
        }
    }

    fun setImageURL(path: String) {
        Thread {
            try {
                val url = URL(path)
                val connection = url.openConnection() as HttpURLConnection
                connection.requestMethod = "GET"
                connection.connectTimeout = 10000

                val code = connection.responseCode
                if (code == 200) {
                    val inputStream = connection.inputStream
                    val bitmap = BitmapFactory.decodeStream(inputStream)

                    val msg = Message.obtain()
                    msg.obj = bitmap
                    msg.what = GET_DATA_SUCCESS
                    handler.sendMessage(msg)

                    inputStream.close()
                } else {
                    handler.sendEmptyMessage(SERVER_ERROR)
                }
            } catch (e: IOException) {
                e.printStackTrace()
                handler.sendEmptyMessage(NETWORK_ERROR)
            }
        }.start()
    }
}
